package cn.j0n4than.accountingtool.utils;

import cn.j0n4than.accountingtool.config.CryptConfig;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * 数据加解密工具
 *
 * @author unknown
 * @see cn.j0n4than.accountingtool.config.CryptConfig
 */
@Component
public class DesUtil {

    private Key key;
    private final String CHARSET_NAME = "UTF-8";
    private final String ALGORITHM = "DES";

    private void init() {
        String keyStr = CryptConfig.KEY;
        try {
            //生成DES算法对象
            KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
            //运用SHA1安全策略
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            //设置上密钥种子
            secureRandom.setSeed(keyStr.getBytes());
            //初始化基于SHA1的算法对象
            generator.init(secureRandom);
            //生成密钥对象
            key = generator.generateKey();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 加密信息
     *
     * @param str 需要加密的字符串
     * @return 加密后的字符串
     */
    public String encrypt(String str) {
        this.init();
        //基于BASE64编码，接收byte[]并转换成String
        Base64.Encoder encoder = Base64.getEncoder();
        try {
            //按utf8编码
            byte[] bytes = str.getBytes(CHARSET_NAME);
            //获取加密对象
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            //初始化密码信息
            cipher.init(Cipher.ENCRYPT_MODE, key);
            //加密
            byte[] doFinal = cipher.doFinal(bytes);
            //byte[]to encode好的String 并返回
            return encoder.encodeToString(doFinal);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 解密信息
     *
     * @param str 需要解密的字符串
     * @return 解密后的字符串
     */
    public String decrypt(String str) {
        this.init();

        Base64.Decoder decoder = Base64.getDecoder();
        try {
            //将字符串decode成byte[]
            byte[] bytes = decoder.decode(str);
            //获取解密对象
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            //初始化解密信息
            cipher.init(Cipher.DECRYPT_MODE, key);
            //解密
            byte[] doFinal = cipher.doFinal(bytes);

            return new String(doFinal, CHARSET_NAME);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
